package com.link.base.base.appinfo.service;

import javax.annotation.Resource;

import com.link.base.base.appinfo.dao.mybatis.mapper.AppManagerMapper;
import com.link.base.base.appinfo.model.AppManager;
import com.link.base.base.appinfo.model.AppVersion;
import com.link.base.core.basic.util.YmlConstants;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.cllog.LCLogger;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;


import java.io.*;
import java.util.List;

/**
 * 移动应用管理
 *
 * @author ouyangzhenqiang
 * @date 2018/11/15
 */
@Service
public class AppManagerServiceImpl extends BasicServiceImpl<AppManager> implements AppManagerService {

    @Resource
    private AppManagerMapper appManagerMapper;

    @Override
    public BasicMapper<AppManager> getBasicMapper() {
        return appManagerMapper;
    }

    @Override
    public void publishApp(AppManager record) throws Exception {
        // 1、动态生成plist文件
        // 移动web网页应用文件目录
        String mobile_web_file_key = "mobile_web_file_path";
        String filePath = PropertyUtil.getProperty(mobile_web_file_key, AppConstants.ADMIN_CORP_ID);
        LCLogger.info().withMessageKey("publishApp").withMessage("移动web网页应用文件目录 => " + filePath).flush();
        // 移动web网页应用http路径前缀
        String mobile_web_http_key = "mobile_web_http_path";
        String httpPath = PropertyUtil.getProperty(mobile_web_http_key, AppConstants.ADMIN_CORP_ID);
        LCLogger.info().withMessageKey("publishApp").withMessage("移动web网页应用http路径前缀 => " + httpPath).flush();
        // 应用发布需生成的plist文件目录路径
        String plistFullDirPath = filePath + "/download/plist/" + record.getBundleId();
        File plistFullDir = new File(plistFullDirPath);
        if (plistFullDir != null && !plistFullDir.exists()) {
            // 不存在则创建目录
            plistFullDir.mkdir();
        }
        // 应用发布需生成的版本发布plist文件完整路径
        String plistFullFilePath = plistFullDirPath + "/app.temp.plist";
        // 应用发布需生成的版本预发布plist文件完整路径
        String plistPlanFilePath = plistFullDirPath + "/app.temp.plan.plist";
        String encoding = "UTF-8";
        File file = new File(filePath);
        // 判断移动web网页应用文件目录是否存在
        if (file != null && file.exists()) {
            String plistTempFilePath = filePath + "/download/template/app.plist";
            File fileTemp = new File(plistTempFilePath);
            // 判断标准plist模版文件是否已上传
            if (fileTemp != null && fileTemp.exists()) {
                // 考虑到编码格式
                try (InputStreamReader read = new InputStreamReader(new FileInputStream(plistTempFilePath), encoding)) {
                    try (BufferedReader bufferedReader = new BufferedReader(read)) {
                        String plist = "";
                        String txt;
                        while ((txt = bufferedReader.readLine()) != null) {
                            plist = plist + txt;
                        }
                        read.close();
                        plist = plist.replace("###57png###", record.getMiniIcon());
                        plist = plist.replace("###512jpg###", record.getAppIcon());
                        plist = plist.replace("###bundleId###", record.getBundleId());
                        plist = plist.replace("###appName###", record.getAppName());
                        try (FileOutputStream out = new FileOutputStream(new File(plistFullFilePath))) {
                            out.write(plist.getBytes());
                            out.close();
                            LCLogger.info().withMessageKey("publishApp").withMessage("版本发布plist文件更新完毕 => " + plist).flush();
                        }
                        try (FileOutputStream out = new FileOutputStream(new File(plistPlanFilePath))) {
                            out.write(plist.getBytes());
                            out.close();
                            LCLogger.info().withMessageKey("publishApp").withMessage("版本预发布plist文件更新完毕 => " + plist).flush();
                        }
                    }
                }
            } else {
                throw new BasicServiceException(plistTempFilePath + "=> 模版文件不存在！");
            }
        } else {
            throw new BasicServiceException(filePath + "文件目录不存在！");
        }

        // 版本发布plist访问路径
        String plistUrl = YmlConstants.getPortalShareUrlDir() + "/mobile/download/plist/" + record.getBundleId() + "/app.plist";
        record.setPlistUrl(plistUrl);
        // 版本预发布plist访问路径
        String plistPlanUrl = YmlConstants.getPortalShareUrlDir() + "/mobile/download/plist/" + record.getBundleId() + "/app.plan.plist";
        record.setPlistUrlPlan(plistPlanUrl);
        // 发布应用下载路径
        String downloadUrl = httpPath + "/appweb/#/download/application/" + record.getId();
        record.setDownloadUrl(downloadUrl);
        // 预发布应用下载路径
        String downloadPlanUrl = httpPath + "/appweb/#/download/application/plan/" + record.getId();
        record.setDownloadUrlPlan(downloadPlanUrl);

        // 2、更新plist文件服务器路径和应用下载地址
        appManagerMapper.updateAppPlistAndDownload(record);

        // 3、更新状态
        record.setStatus("AppAlreadyRelease");
        appManagerMapper.appStatusUpdate(record);

        // 4、设置redis变量
        publishAppSetRedisInfo(record);
    }

    @Override
    public void publishAppSetRedisInfo(AppManager record) throws Exception {
        // 将应用基本信息写如Redis
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            // redis key
            String appInfoRedisKey = "app_info_" + record.getBundleId();
            // 应用名称
            j.hset(appInfoRedisKey, "appName", StringUtils.null2EmptyString(record.getAppName()));
            // 应用bundle Id
            j.hset(appInfoRedisKey, "bundleId", StringUtils.null2EmptyString(record.getBundleId()));
            // 应用介绍
            j.hset(appInfoRedisKey, "appDesc", StringUtils.null2EmptyString(record.getAppDesc()));
            // 应用图标 512
            j.hset(appInfoRedisKey, "appIcon", StringUtils.null2EmptyString(record.getAppIcon()));
            // 应用小图标 57
            j.hset(appInfoRedisKey, "appMiniIcon", StringUtils.null2EmptyString(record.getMiniIcon()));
            // 应用预览图1
            j.hset(appInfoRedisKey, "appPreviewImg1", StringUtils.null2EmptyString(record.getFirstPreviewUrl()));
            // 应用预览图2
            j.hset(appInfoRedisKey, "appPreviewImg2", StringUtils.null2EmptyString(record.getSecondPreviewUrl()));
            // 应用预览图3
            j.hset(appInfoRedisKey, "appPreviewImg3", StringUtils.null2EmptyString(record.getThirdPreviewUrl()));
            // 应用预览图4
            j.hset(appInfoRedisKey, "appPreviewImg4", StringUtils.null2EmptyString(record.getForthPreviewUrl()));
            // 应用发布状态
            j.hset(appInfoRedisKey, "appReleaseStatus", StringUtils.null2EmptyString(record.getStatus()));
            // 版本发布plist访问路径
            j.hset(appInfoRedisKey, "appPlistUrl", StringUtils.null2EmptyString(record.getPlistUrl()));
            // 版本发布应用下载路径
            j.hset(appInfoRedisKey, "appDownloadUrl", StringUtils.null2EmptyString(record.getDownloadUrl()));
            // 版本预发布plist访问路径
            j.hset(appInfoRedisKey, "appPlistUrlPlan", StringUtils.null2EmptyString(record.getPlistUrlPlan()));
            // 版本预发布应用下载路径
            j.hset(appInfoRedisKey, "appDownloadUrlPlan", StringUtils.null2EmptyString(record.getDownloadUrlPlan()));
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    @Override
    public void soldOutApp(AppManager record) throws Exception {
        record.setStatus("AppAlreadySoldOut");
        appManagerMapper.appStatusUpdate(record);
        // 更新redis
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            // redis key
            String appInfoRedisKey = "app_info_" + record.getBundleId();
            // 应用发布状态
            j.hset(appInfoRedisKey, "appReleaseStatus", StringUtils.null2EmptyString(record.getStatus()));
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    @Override
    public List<AppManager> getAppList(AppManager record) throws Exception {
        record.setLoginCorpId(0L);
        List<AppManager> list = appManagerMapper.queryAll(record);
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            // 设置应用最新的版本记录信息，直接从redis中获取
            for (AppManager item : list) {
                String appInfoRedisKey = "app_info_" + item.getBundleId();
                AppVersion version = new AppVersion();
                version.setAppType(j.hget(appInfoRedisKey, "bundleId"));
                // 企业级大版本号
                version.setAppLV(j.hget(appInfoRedisKey, "appLV"));
                // 企业级小版本号
                version.setAppMV(j.hget(appInfoRedisKey, "appMV"));
                // 版本更新提示
                version.setUpdateTips(j.hget(appInfoRedisKey, "updateTips"));
                // iOS更新包大小
                version.setIpaSize(j.hget(appInfoRedisKey, "ipaSize"));
                // 安卓更新包大小
                version.setApkSize(j.hget(appInfoRedisKey, "apkSize"));
                // 版本更新日期
                version.setUpdateDt(j.hget(appInfoRedisKey, "updateDt"));
                // apk下载地址
                version.setApkUrl(j.hget(appInfoRedisKey, "apkDownloadUrl"));
                // ipa下载地址
                version.setIpaUrl(j.hget(appInfoRedisKey, "ipaDownloadUrl"));
                version.setAnonymousFlag("Y");
                item.setVersion(version);
                item.setAnonymousFlag("Y");
            }
        } finally {
            RedisUtil.returnResource(j);
        }
        return list;
    }

    @Override
    public AppManager getAppById(AppManager record) throws Exception {
        LinkRedisClient j = null;
        try {
            record.setLoginCorpId(0L);
            // 区分查询应用为发布/预发布
            String releaseStatus = record.getStatus();
            if (StringUtils.isBlank(releaseStatus)) {
                releaseStatus = "release";
            }
            AppManager temp = appManagerMapper.queryById(record);
            String bundleId = temp.getBundleId();
            j = RedisUtil.getJedis();
            String appInfoRedisKey = "app_info_" + bundleId;
            // 应用信息
            record.setId(temp.getId());
            record.setAppName(j.hget(appInfoRedisKey, "appName"));
            record.setBundleId(j.hget(appInfoRedisKey, "bundleId"));
            record.setAppDesc(j.hget(appInfoRedisKey, "appDesc"));
            record.setAppIcon(j.hget(appInfoRedisKey, "appIcon"));
            record.setMiniIcon(j.hget(appInfoRedisKey, "appMiniIcon"));
            record.setFirstPreviewUrl(j.hget(appInfoRedisKey, "appPreviewImg1"));
            record.setSecondPreviewUrl(j.hget(appInfoRedisKey, "appPreviewImg2"));
            record.setThirdPreviewUrl(j.hget(appInfoRedisKey, "appPreviewImg3"));
            record.setForthPreviewUrl(j.hget(appInfoRedisKey, "appPreviewImg4"));
            record.setStatus(j.hget(appInfoRedisKey, "appReleaseStatus"));
            // 版本信息
            AppVersion version = new AppVersion();
            if ("release".equals(releaseStatus)) {
                // 提供发布应用信息
                record.setPlistUrl(j.hget(appInfoRedisKey, "appPlistUrl"));
                record.setDownloadUrl(j.hget(appInfoRedisKey, "appDownloadUrl"));
                version.setAppLV(j.hget(appInfoRedisKey, "appLV"));
                version.setAppMV(j.hget(appInfoRedisKey, "appMV"));
                version.setUpdateTips(j.hget(appInfoRedisKey, "updateTips"));
                version.setIpaSize(j.hget(appInfoRedisKey, "ipaSize"));
                version.setApkSize(j.hget(appInfoRedisKey, "apkSize"));
                version.setUpdateDt(j.hget(appInfoRedisKey, "updateDt"));
                version.setApkUrl(j.hget(appInfoRedisKey, "apkDownloadUrl"));
                version.setIpaUrl(j.hget(appInfoRedisKey, "ipaDownloadUrl"));
            } else {
                // 提供预发布应用信息
                record.setPlistUrl(j.hget(appInfoRedisKey, "appPlistUrlPlan"));
                record.setDownloadUrl(j.hget(appInfoRedisKey, "appDownloadUrlPlan"));
                version.setAppLV(j.hget(appInfoRedisKey, "appLVPlan"));
                version.setAppMV(j.hget(appInfoRedisKey, "appMVPlan"));
                version.setUpdateTips(j.hget(appInfoRedisKey, "updateTipsPlan"));
                version.setIpaSize(j.hget(appInfoRedisKey, "ipaSizePlan"));
                version.setApkSize(j.hget(appInfoRedisKey, "apkSizePlan"));
                version.setUpdateDt(j.hget(appInfoRedisKey, "updateDtPlan"));
                version.setApkUrl(j.hget(appInfoRedisKey, "apkDownloadUrlPlan"));
                version.setIpaUrl(j.hget(appInfoRedisKey, "ipaDownloadUrlPlan"));
            }
            version.setAnonymousFlag("Y");
            record.setVersion(version);
            record.setAnonymousFlag("Y");
        } finally {
            RedisUtil.returnResource(j);
        }
        return record;
    }
}

